package com.atguigu.daijia.payment.controller;

import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.model.form.payment.PaymentInfoForm;
import com.atguigu.daijia.model.vo.payment.WxPrepayVo;
import com.atguigu.daijia.payment.service.WxPayService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@Tag(name = "微信支付接口")
@RestController
@RequestMapping("payment/wxPay")
@Slf4j
@RequiredArgsConstructor
public class WxPayController {

    private final WxPayService wxPayService;

    /**
     * 调用微信 JSAPI 下单接口，获取预支付交易会话标识
     * @param paymentInfoForm
     * @return
     */
    @Operation(summary = "调用微信 JSAPI 下单接口，获取预支付交易会话标识")
    @PostMapping("/createJsapi")
    public Result<WxPrepayVo> createWxPayment(@RequestBody PaymentInfoForm paymentInfoForm) {
        WxPrepayVo wxPrepayVo = wxPayService.createWxPayment(paymentInfoForm);
        return Result.ok(wxPrepayVo);
    }

    /**
     * 查询订单支付状态
     * @param orderNo
     * @return
     */
    @Operation(summary = "查询订单支付状态")
    @GetMapping("/queryPayStatus/{orderNo}")
    public Result<Boolean> queryPayStatus(@PathVariable("orderNo") String orderNo) {
        Boolean result = wxPayService.queryPayStatus(orderNo);
        return Result.ok(result);
    }

    /**
     * 微信支付结果异步通知
     * @param request 微信异步通知请求
     * @return
     */
    @Operation(summary = "微信支付结果异步通知")
    @PostMapping("/notify")
    public Map<String, Object> notify(HttpServletRequest request) {
        try {
            wxPayService.wxNotify(request);
            // 通知微信服务器，已经收到信息
            HashMap<String, Object> result = new HashMap<>();
            result.put("code", "SUCCESS");
            result.put("message", "成功");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 通知微信服务器，未收到信息
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", "FAIL");
        result.put("message", "失败");
        return result;
    }
}
